package com.cola.custSpeechTranscription.model;

import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @BelongsProject: custSpeechTranscription
 * @BelongsPackage: com.cola.custSpeechTranscription.model
 * @Author: jiangkang
 * @CreateTime: 2025-10-30  15:10
 * @Description: TODO
 * @Version: 1.0
 */
public class CustShareSession {
    private final String shareId;
    private final UserSession ownerUserSession;
    private final Map<String, WebSocketSession> viewSessions = new ConcurrentHashMap<>(); // viewerUserId -> WebSocketSession
    private final long createTime = System.currentTimeMillis();

    private static final Logger log = LoggerFactory.getLogger("LCAP_EXTENSION_LOGGER");

    public CustShareSession(String shareId, UserSession ownerUserSession) {
        this.shareId = shareId;
        this.ownerUserSession = ownerUserSession;
    }

    public void addViewSession(WebSocketSession session, String viewerUserId) {
        viewSessions.put(viewerUserId, session);
        log.info("[添加观看会话] shareId={}, viewerUserId={}, 当前观看人数={}",
                shareId, viewerUserId, viewSessions.size());
    }

    public void removeViewSession(WebSocketSession session) {
        viewSessions.entrySet().removeIf(entry -> entry.getValue().equals(session));
    }

    public boolean isEmpty() {
        return viewSessions.isEmpty();
    }

    public void broadcastToViewers(String message) {
        Iterator<Map.Entry<String, WebSocketSession>> iterator = viewSessions.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry<String, WebSocketSession> entry = iterator.next();
            WebSocketSession session = entry.getValue();
            if (session.isOpen()) {
                try {
                    session.sendMessage(new TextMessage(message));
                } catch (IOException e) {
                    log.error("[广播消息] 发送到观看会话失败 viewerUserId={}", entry.getKey(), e);
                    iterator.remove();
                }
            } else {
                iterator.remove();
            }
        }
    }

    /**
     * 关闭所有观看者连接
     */
    public void closeAllViewerSessions() {
        log.info("[关闭所有观看者连接] shareId={}, 观看者数量={}", shareId, viewSessions.size());

        for (Map.Entry<String, WebSocketSession> entry : viewSessions.entrySet()) {
            WebSocketSession session = entry.getValue();
            if (session.isOpen()) {
                try {
                    session.close(CloseStatus.NORMAL.withReason("分享会话已结束"));
                    log.info("[关闭观看者连接] viewerUserId={}, sessionId={}", entry.getKey(), session.getId());
                } catch (IOException e) {
                    log.error("[关闭观看者连接] 失败 viewerUserId={}", entry.getKey(), e);
                }
            }
        }
        viewSessions.clear();
    }

    /**
     * 移除观看会话（按用户ID）
     */
    public void removeViewSessionByUserId(String viewerUserId) {
        WebSocketSession removed = viewSessions.remove(viewerUserId);
        if (removed != null) {
            log.info("[移除观看会话] shareId={}, viewerUserId={}, 剩余观看人数={}",
                    shareId, viewerUserId, viewSessions.size());
        }
    }

    public void sendHistoryToSession(WebSocketSession session) {
        if (session.isOpen()) {
            try {
                // 发送会话信息
                JSONObject sessionInfo = new JSONObject();
                sessionInfo.put("type", "session_info");
                sessionInfo.put("shareId", shareId);
                sessionInfo.put("ownerUserId", ownerUserSession.getUserId());
                sessionInfo.put("createTime", createTime);
                sessionInfo.put("viewerCount", getViewerCount());
                session.sendMessage(new TextMessage(sessionInfo.toString()));

                // 发送历史转写记录
                List<String> transcripts = ownerUserSession.getTranscripts();
                for (String transcript : transcripts) {
                    session.sendMessage(new TextMessage(transcript));
                }
                log.info("[发送历史] 向会话发送了 {} 条历史记录", transcripts.size());
            } catch (IOException e) {
                log.error("[发送历史] 失败", e);
            }
        }
    }

    // Getters
    public String getShareId() { return shareId; }
    public UserSession getOwnerUserSession() { return ownerUserSession; }
    public int getViewerCount() { return viewSessions.size(); }
    public long getCreateTime() { return createTime; }
}